package org.mineground.commands.player.admin;

import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.mineground.Main;
import org.mineground.PermissionNodes;
import org.mineground.Utilities;

/**
 * @name Give.java
 * @author Daniel Koenen (2012)
 */
public class Give implements CommandExecutor {
	@Override
	public boolean onCommand(CommandSender cs, Command cmnd, String string,
			String[] arguments) {
		Player player = (Player) cs;

		if (!player.hasPermission(PermissionNodes.PERMISSION_GIVE_COMMAND)) {
			return true;
		}

		if (arguments.length == 0) {
			player.sendMessage(ChatColor.RED
					+ "* Usage: '/i <player> <blockid/name> <quantity>'");
			return true;
		}

		Player givePlayer = Main.getInstance().getServer()
				.getPlayer(arguments[0]);
		
		if (givePlayer == null) {
			player.sendMessage(ChatColor.RED + "* Error: Invalid user.");
			return true;
		}

		if (givePlayer.getWorld() == Main
				.getInstance()
				.getServer()
				.getWorld(
						Main.getInstance().getConfigHandler().getSurvivalWorldName())
				|| givePlayer.getWorld() == Main
						.getInstance()
						.getServer()
						.getWorld(
								Main.getInstance().getConfigHandler().getSurvivalNetherWorldName())) {
			player.sendMessage(ChatColor.RED + "YOU FUCKING CHEATER!");
			return true;
		}
		
		if (!givePlayer.getCanPickupItems()) {
			player.sendMessage("The player cannot carry anymore items");
			givePlayer.sendMessage("Someone wants to give items to you, but your inventory is full");
			return true;
		}

		PlayerInventory inventory;
		Material blockMaterial;
		String blockId = arguments[1];

		int blockAmount = Integer.parseInt(arguments[2]);

		if (Utilities.isNumeric(blockId)) {
			blockMaterial = Material.getMaterial(blockId);
			
		}

		else {
			blockMaterial = Material.getMaterial(blockId.toUpperCase());
		}

		if (blockMaterial == null) {
			player.sendMessage(ChatColor.RED + "* Error: Invalid item.");
			return true;
		}

		inventory = givePlayer.getInventory();
		ItemStack newItem = new ItemStack(blockMaterial);
		newItem.setAmount(blockAmount);
		inventory.addItem(newItem);

		givePlayer.sendMessage(ChatColor.GOLD + player.getName()
				+ " has given you " + blockAmount + " of "
				+ blockMaterial.toString().toLowerCase() + ".");
		player.sendMessage(ChatColor.DARK_GREEN + "You have given "
				+ givePlayer.getName() + " " + blockAmount + " of "
				+ blockMaterial.toString().toLowerCase() + ".");
		return true;
	}
}
